package ks32.crosswalk_native;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.freeview.fvadpter.callController.CallController;
import com.pakdata.xwalk.refactor.XWalkPreferences;
import com.pakdata.xwalk.refactor.XWalkSettings;
import com.pakdata.xwalk.refactor.XWalkView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.chromium.base.Log;
import org.xwalk.core.XWalkInitializer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity  implements XWalkInitializer.XWalkInitListener , CallController.CallControllerListener{
    private XWalkView mXWalkView;
    private XWalkInitializer mXWalkInitializer;
    public SoundPool sp;
    FrameLayout parent;
    ImageButton fab;
    MainActivity wcontexts;
    /*String url = "http://172.16.20.209/daping/#/";/*/
    /*http://181.181.180.139/daping/#/BigScreen*/
    String url = "http://192.168.8.48/daping/index.html";
    String urle = "http://192.168.8.48/daping/#/BigScreen";
    Boolean ThirdPartyNotUrl = false; //是否为第三方url
    public int MessageReceived  = 0; // 是否收到webview消息
    private Timer timer = new Timer(true);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startService(new Intent(this,KeepLifeService.class));
        /*禁用底部菜单*/
        Window _window = getWindow();
        WindowManager.LayoutParams params = _window.getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
        _window.setAttributes(params);
        /*end*/
        CallController.getInstance().addListener(this);
        setContentView(R.layout.activity_main);
        mXWalkInitializer = new XWalkInitializer(this, this);
        mXWalkInitializer.initAsync();
        XWalkPreferences.setValue("enable-javascript", true);
        XWalkPreferences.setValue(XWalkPreferences.ALLOW_UNIVERSAL_ACCESS_FROM_FILE, true);
        requestPermissioner();
        wcontexts = this;
        fab = findViewById(R.id.fab);
        fab.setVisibility(View.GONE);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mXWalkView.loadUrl("javascript:location.href='"+urle+"'");
                fab.setVisibility(View.GONE);

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.v("llll","666666");
    }
        /*全视通串口监听*/
    @Override
    public boolean onInterceptCommandEvent() {
        return false;
    }

    /**
     * 监听按钮键值
     * @param keyCode
     * keyCode = 32 呼叫护士
     */
    @Override
    public void onCommandCommand(int keyCode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mXWalkView.loadUrl("javascript:cxylOnkeyUp('"+keyCode+"')");
            }
        });
    }
    /*end*/

    private void init(){
        initSettings();
        setGlobalUncaughtExceptionHandler();
        timer.schedule(task, 1, 5*60*1000);
        mXWalkView.addJavascriptInterface(new jsApi(MainActivity.this,mXWalkView), "Plusdx");
        mXWalkView.addJavascriptInterface(new MinPlus(), "MinPlus");  // 建立通讯桥梁
        mXWalkView.getSettings().setAppCacheEnabled(true);

    }
    //获取总内存的大小

    private TimerTask task = new TimerTask() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        public void run() {
            Log.v("kkkk",""+111);
            if(ThirdPartyNotUrl == true){
                MessageReceived = 1;
            }
            if(MessageReceived == 2){
                Intent newIntent = new Intent(MainActivity.this, MainActivity.class);  // 要启动的Activity
                newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MainActivity.this.startActivity(newIntent);
                System.exit(0);
            }
            MessageReceived = 2;
        }
    };
    public   void setGlobalUncaughtExceptionHandler() {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                Log.v("kkkkk","UnCaughtException"+e);
                Intent newIntent = new Intent(MainActivity.this, MainActivity.class);  // 要启动的Activity
                newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MainActivity.this.startActivity(newIntent);
                System.exit(0);
            }
        });
    }

    public class MinPlus {
        /*心跳检测是否死机*/
        /*监听页面是否卡死了*/
        @JavascriptInterface
        public void onJsFunctionCalled()  {
            MessageReceived = 1; //收到消息了
        }
        @JavascriptInterface
        public void testtuichu(){
            Intent newIntent = new Intent(MainActivity.this, MainActivity.class);  // 要启动的Activity
            newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MainActivity.this.startActivity(newIntent);
            System.exit(0);
        }
        @JavascriptInterface
        public void Xrestart() {
            /*System.exit(0);*/
            Intent newIntent = new Intent(MainActivity.this, MainActivity.class);  // 要启动的Activity
            newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MainActivity.this.startActivity(newIntent);
            System.exit(0);
        }

        /*获取mac地址 和ip地址 以及设备唯一编码   返回逗号隔开*/
        @JavascriptInterface
        public void getLocalMacAddressFromIp() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String ANDROID_ID = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
                    mXWalkView.loadUrl("javascript:getLocalMacAddressFromIp('" + equipmentInformation.getLocalMacAddressFromIp() + "," + equipmentInformation.getLocalInetAddress() + "," + ANDROID_ID + ","+jsApi.getVersionCode( wcontexts)+"')");
                }
            });
        }
        @JavascriptInterface
        public void hideBackbtn(){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ThirdPartyNotUrl = false;
                    fab.setVisibility(View.GONE);
                }
            });

        }
        @JavascriptInterface
        public void showBackbtn(){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ThirdPartyNotUrl = true;
                    fab.setVisibility(View.VISIBLE);
                }
            });

        }
    }
    private void requestPermissioner() {
        AndPermission.with(MainActivity.this)
                .permission(Permission.RECORD_AUDIO,Permission.CAMERA)
                // 准备方法，和 okhttp 的拦截器一样，在请求权限之前先运行改方法，已经拥有权限不会触发该方法
                .rationale((context, permissions, executor) -> {
                    // 此处可以选择显示提示弹窗
                    executor.execute();
                })
                // 用户给权限了
                .onGranted(permissions -> Log.v("qqq4", "设置权限了"))
                // 用户拒绝权限，包括不再显示权限弹窗也在此列
                .onDenied(permissions -> {
                    // 判断用户是不是不再显示权限弹窗了，若不再显示的话进入权限设置页
                    if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, permissions)) {
                        // 打开权限设置页
                        AndPermission.permissionSetting(MainActivity.this).execute();
                        return;
                    }
                })
                .start();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.v("qqq4", "qqq4");
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onBackPressed() {
        Log.i("qqq3","mContext");
        parent = (FrameLayout) findViewById(R.id.parentMain);
        parent.removeAllViews();
        super.onBackPressed();

    }

    @Override
    public void onXWalkInitStarted() {
        Log.i("qqq2","onXWalkInitStarted");

    }

    @Override
    public void onXWalkInitCancelled() {
        Log.i("qqq","onXWalkInitCancelled");
    }

    @Override
    public void onXWalkInitFailed() {
        Log.i("qqq1","onXWalkInitFailed");

    }


    /**
     * 没有允许定位的设置
     */
    public void initSettings() {
        XWalkSettings webSettings = mXWalkView.getSettings();
        //启用JavaScript
        webSettings.setJavaScriptEnabled(true);
        //允许js弹窗alert等，window.open方法打开新的网页，默认不允许
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        //localStorage和sessionStorage
        webSettings.setDomStorageEnabled(true);
        //Web SQL Databases
        webSettings.setDatabaseEnabled(true);
        //是否可访问Content Provider的资源，默认值 true
        webSettings.setAllowContentAccess(true);

        /*
        是否允许访问文件系统，默认值 true
        file:///androMSG_asset和file:///androMSG_res始终可以访问，不受其影响
         */
        webSettings.setAllowFileAccess(true);
        //是否允许通过file url加载的Javascript读取本地文件，默认值 false
        webSettings.setAllowFileAccessFromFileURLs(true);
        //是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
        webSettings.setAllowUniversalAccessFromFileURLs(true);

        //设置是否支持缩放
        webSettings.setSupportZoom(false);
        //设置内置的缩放控件
        webSettings.setBuiltInZoomControls(false);

        /*
         当该属性被设置为false时，加载页面的宽度总是适应WebView控件宽度；
         当被设置为true，当前页面包含viewport属性标签，在标签中指定宽度值生效，如果页面不包含viewport标签，无法提供一个宽度值，这个时候该方法将被使用。
         */
        webSettings.setUseWideViewPort(true);
        //缩放至屏幕大小
         webSettings.setLoadWithOverviewMode(true);
        //支持多窗口
        webSettings.setSupportMultipleWindows(true);

        /*
        缓存模式
        LOAD_CACHE_ONLY         不使用网络，只读取本地缓存
        LOAD_DEFAULT            根据cache-control决定是否从网络上获取数据
        LOAD_NO_CACHE           不使用缓存，只从网络获取数据
        LOAD_CACHE_ELSE_NETWORK 只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据
         */
        webSettings.setCacheMode(XWalkSettings.LOAD_DEFAULT);
        //设置是否加载图片
        webSettings.setLoadsImagesAutomatically(true);

        //允许远程调试
        XWalkPreferences.setValue("enable-javascript", true);
        XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true);
    }


    class MyWebViewClient extends WebViewClient {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if(url.contains("cordova.js")){//加载指定.js时 引导服务端加载本地Assets/www文件夹下的cordova.js
                try {
                    return new WebResourceResponse("application/x-javascript","utf-8",getBaseContext().getAssets().open("www/cordova.js"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return super.shouldInterceptRequest(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if(request.getUrl().toString().contains("cordova.js")){//加载指定.js时 引导服务端加载本地Assets/www文件夹下的cordova.js
                    try {
                        return new WebResourceResponse("application/x-javascript","utf-8",getBaseContext().getAssets().open("www/cordova.js"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return super.shouldInterceptRequest(view, request);
        }

    }

    @Override
    public void onXWalkInitCompleted() {
        Log.i("qqq5","onXWalkInitCompleted");
        mXWalkView = new XWalkView(this);
        init();
        mXWalkView.clearCache(true);
        parent = (FrameLayout) findViewById(R.id.parentMain);
        parent.addView(mXWalkView);
//        mXWalkView.load("http://192.168.104.135:8080","");
       mXWalkView.load(url,"");
       /* mXWalkView.load("file:///android_asset/web/index.html#/",""); */

       // mXWalkView.clearCache(true);
    }

}